package com.litian.dancechar.gateway.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.litian.dancechar.framework.common.base.RespResult;
import com.litian.dancechar.gateway.feign.base.client.BaseServiceClient;
import com.litian.dancechar.gateway.feign.base.dto.SysBlackListReqDTO;
import com.litian.dancechar.gateway.feign.base.dto.SysBlackListRespDTO;
import com.litian.dancechar.gateway.feign.base.dto.SysWhiteListReqDTO;
import com.litian.dancechar.gateway.feign.base.dto.SysWhiteListRespDTO;
import com.litian.dancechar.gateway.service.BlackListService;
import com.litian.dancechar.gateway.service.WhiteListService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 刷新定时任务
 *
 * @author litian
 * @date 2021/6/22 09:51
 */
@Component
@EnableScheduling
@Slf4j
public class RefreshWhiteBlackListJob {
    @Resource
    private BaseServiceClient baseServiceClient;

    @Scheduled(fixedRate = 6000)
    public void refresh() {
        refreshWhiteList();
        refreshBlackList();
    }

    /**
     * 刷新黑名单列表
     */
    private void refreshBlackList() {
        try {
            SysBlackListReqDTO reqDTO = new SysBlackListReqDTO();
            RespResult<List<SysBlackListRespDTO>> result = baseServiceClient.findBlackList(reqDTO);
            if (result.isOk() && CollUtil.isNotEmpty(result.getData())) {
                BlackListService.blackListArrayList.clear();
                BlackListService.blackListArrayList = result.getData().stream().map(SysBlackListRespDTO::getReqUrl)
                        .collect(Collectors.toList());
                log.info("当前系统黑名单列表:{}", JSONUtil.toJsonStr(BlackListService.blackListArrayList));
            }
        } catch (Exception e) {
            log.error("查询缓存黑名单异常！errMsg:{}", e.getMessage(), e);
        }
    }

    /**
     * 刷新白名单列表
     */
    private void refreshWhiteList() {
        try {
            SysWhiteListReqDTO reqDTO = new SysWhiteListReqDTO();
            RespResult<List<SysWhiteListRespDTO>> result = baseServiceClient.findWhiteList(reqDTO);
            if (result.isOk() && CollUtil.isNotEmpty(result.getData())) {
                WhiteListService.whiteListArrayList.clear();
                WhiteListService.whiteListArrayList = result.getData().stream().map(SysWhiteListRespDTO::getReqUrl)
                        .collect(Collectors.toList());
                log.info("当前系统白名单列表:{}", JSONUtil.toJsonStr(WhiteListService.whiteListArrayList));
            }
        } catch (Exception e) {
            log.error("查询缓存白名单异常！errMsg:{}", e.getMessage(), e);
        }
    }
}